package com.webapp.dao;

import java.util.List;

import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import com.webapp.domain.entity.Message;
import com.webapp.domain.entity.Session;
@Repository("messageDAO")
public class MessageDAO extends AbstractDAO<Message>{

	
	
	/**
	 * 根据会话查询聊天记录
	 * @param session
	 * @return
	 */
	public List<Message> findMessageBySession(Session session){
		return this.find("where message.session = ? order by create_time asc", session);
	}

	
	
	/**
	 * 查询咨询师消息记录数
	 * @param disputesId
	 * @param counselorId
	 * @return
	 */
	public int getCountMessageByCounselor(long disputesId,long  counselorId){
		String sql = "SELECT COUNT(0) FROM MESSAGE m LEFT JOIN SESSION s ON m.session_id = s.id "+
				 "WHERE s.disputes_id= ? AND s.counselor_id = ? AND m.sender='1'";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, disputesId);
		query.setParameter(1, counselorId);
		Object obj = query.uniqueResult();
		return Integer.parseInt(obj.toString());
	}
	/**
	 * 查询用户消息记录数
	 * @param disputesId
	 * @param counselorId
	 * @return
	 */
	public int getCountMessageByUser(long disputesId,long  counselorId){
		String sql = "SELECT COUNT(0) FROM MESSAGE m LEFT JOIN SESSION s ON m.session_id = s.id "+
				"WHERE s.disputes_id= ? AND s.counselor_id = ? AND m.sender='0'";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, disputesId);
		query.setParameter(1, counselorId);
		Object obj = query.uniqueResult();
		return Integer.parseInt(obj.toString());
	}
	/**
	 * 将一个人一个会话的未读信息修改为已读
	 * @param sessionId  会话id
	 * @param sender     发送人标记，0用户发送，1咨询师发送
	 * @return 修改的记录数
	 */
	public synchronized int updataCode(long sessionId,String sender){
		String sql = "UPDATE MESSAGE SET IS_READ=TRUE WHERE SESSION_ID = ? AND sender=? AND IS_READ=FALSE ";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, sessionId);
		query.setParameter(1, sender);
		return query.executeUpdate();
	}
	/**
	 * 查询一个会话咨询师发送第一条记录的时间
	 * @param sessionId
	 * @return
	 */
	public String counselor_message_min(long sessionId){
		String sql = "SELECT MIN(m.CREATE_TIME) FROM MESSAGE m "+
		"LEFT JOIN SESSION s ON m.SESSION_ID = s.ID "+
		"WHERE m.SENDER = '1' AND s.ID = ?";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, sessionId);
		Object obj = query.uniqueResult();
		if (obj == null) {
			return null;
		}else{
			return String.valueOf(obj);
		}
		
	}
	
	
	
}
